package com.irdstudio.efp.esb.api.rest.yed.interfaceManage;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.efp.console.service.facade.PrdInfoService;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.cus.service.vo.CusIndivVO;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.rest.yed.req.ReqRepayAcctChangeBean;
import com.irdstudio.efp.esb.api.rest.yed.resp.RespRepayAcctChangeBean;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 需求编号：【2019D0509】（业务提的需求编号）
 * 问题编号：【】（若不是因为修复问题而新增该类，则留空）
 * 开发人员：【wanglh4】
 * 创建日期：【2020/8/3 9:47】
 * 功能描述：
 */
public class RepayAcctChangeController implements FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(RepayAcctChangeController.class);


    /**
     * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("校验 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("reqPersonalLoanInfo")
    public ReqRepayAcctChangeBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("校验 ESB请求体对象！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqRepayAcctChangeBean.class, Feature.InternFieldNames);
    }

    /**
     *  此接口是渠道端调用网贷，网贷将还款账户变更更新到用信表，更新完成调用互金，将客户九要素以及还款账户变更送给互金。
     *
     * @author xieziwei
     * @date 2020/8/3 9:56
     * @version 0.1
     */
    // todo esb服务码
    @PostMapping("/SERVICE_todo")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqPersonalLoanInfo") ReqRepayAcctChangeBean reqRepayAcctChangeBean, BindingResult br2, Exception exception) {
        logger.info("调用还款账号变更接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        RespRepayAcctChangeBean respRepayAcctChangeBean = new RespRepayAcctChangeBean();
        try{
            // 产品信息校验
            PrdInfoVO inPrdInfoVO = new PrdInfoVO();
            inPrdInfoVO.setPrdCode(reqRepayAcctChangeBean.getPrdId());
            PrdInfoVO prdInfoVO = prdInfoService.queryValidPrdInfo(inPrdInfoVO);
            if (Objects.isNull(prdInfoVO)){
                logger.warn("【还款账号变更接口】产品信息不存在或不为生效状态！请核查产品信息重试。");
                throw new Exception("【还款账号变更接口】产品信息不存在或不为生效状态！请核查产品信息重试。");
            }
            // 客户信息校验
            CusIndivVO inCusIndivVO = new CusIndivVO();
            inCusIndivVO.setCertCode(reqRepayAcctChangeBean.getCertCode());
            CusIndivVO cusIndivVO = cusIndivService.queryByCondition(inCusIndivVO);
            if (Objects.isNull(cusIndivVO)){
                logger.warn("【还款账号变更接口】客户信息不存在！请核查客户信息重试。");
                throw new Exception("【还款账号变更接口】客户信息不存在！请核查客户信息重试。");
            }
            // 客户用信信息校验
            NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO();
            nlsApplyInfoVO.setCertCode(reqRepayAcctChangeBean.getCertCode());
            nlsApplyInfoVO.setPrdId(reqRepayAcctChangeBean.getPrdId());
            nlsApplyInfoVO.setRecvAcctNo(reqRepayAcctChangeBean.getRecvAcctNo());
            nlsApplyInfoVO.setRecvBankName(reqRepayAcctChangeBean.getRecvBankName());
            int count = nlsApplyInfoService.queryCountByCertCode(nlsApplyInfoVO);
            if (count<0){
                logger.warn("【还款账号变更接口】根据证件号码查询用信信息为空！请核查证件号码重试。");
                throw new Exception("【还款账号变更接口】根据证件号码查询用信信息为空！请核查证件号码重试。");
            }
            // 更新
            int num = nlsApplyInfoService.updateAcctNoByCertCode(nlsApplyInfoVO);
            if (count == num ){
                logger.info("【还款账号变更接口】，更新用信信息表中数据成功！");
            }
            // 客户授信信息校验
            NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
            nlsCreditInfoVO.setCertCode(reqRepayAcctChangeBean.getCertCode());
            nlsCreditInfoVO.setPrdId(reqRepayAcctChangeBean.getPrdId());
            List<NlsCreditInfoVO> nlsCreditInfoVOS = nlsCreditInfoService.queryCertCode(nlsCreditInfoVO);
            if (nlsCreditInfoVOS.size() != 1){
                logger.warn("【还款账号变更接口】根据证件号码查询授信信息为空！请核查证件号码重试。");
                throw new Exception("【还款账号变更接口】根据证件号码查询授信信息为空！请核查证件号码重试。");
            }
            int mnum = nlsCreditInfoService.updateAcctNo(nlsCreditInfoVO);
            if (mnum == 1 ){
                logger.info("【还款账号变更接口】，更新授信信息表中数据成功！");
            }
            //todo
            //将客户九要素以及还款账户变更送给互金

            //返回报文
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSONObject.toJSONString(respRepayAcctChangeBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero),
                    EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                    EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                    "查询成功");


        }catch (Exception e){
            logger.error("借据信息查询接口出现异常，异常信息为：[{}]", e.getMessage());
            e.printStackTrace();
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSONObject.toJSONString(respRepayAcctChangeBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteMapNullValue),
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                    EsbRetCodeStandard.SJCLYC.getValue(),
                    exception.getMessage());
        }

    }

    @Autowired
    @Qualifier("prdInfoService")
    private PrdInfoService prdInfoService;

    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;

    @Autowired
    @Qualifier("nlsApplyInfoService")
    private NlsApplyInfoService nlsApplyInfoService;

    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;

}
